<?php

    include('dboper.php');
    $d_sistem = getConfig();
    $tmp = getResults();
    echo '<h4>IPK Asisten Praktikum</h4>';
    echo '<br><button id="simpan" >&#9658; Download</button><div><table id="data">';
    echo '<tr><td>NIM</td><td>Nama</td><td>IPK</td><td>Bar</td></tr>';
    while ($rst = mysql_fetch_array($tmp)) {
        echo "<tr><td>".$rst['nim']."</td><td>".$rst['nama']."</td><td>".$rst['TOTAL']."</td><td><div style='width:".($rst['TOTAL']*50)."px;' id='bar'>&nbsp;</div></td></tr>"; 
    }
    echo '</table></div>';

?>
<script>
    function browserTester(browserString) {
		return navigator.userAgent.toLowerCase().indexOf(browserString) > -1;
	}
    $("#simpan").click(function(e){
        var a = document.createElement('a');
        //getting data from our div that contains the HTML table
        var data_type = 'data:application/vnd.ms-excel;';
        var makul = '<?php echo $d_sistem["matakuliah"]; ?>';
        var kelas = '<?php echo $d_sistem["kelas"]; ?>';
        var table_div = document.getElementById('data');
		var uri = 'data:application/vnd.ms-excel;base64,'
		, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>Matakuliah : '+makul+' | Kelas : '+kelas+'<table>{table}</table></body></html>'
		, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
		, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }

        var table_html = table_div.outerHTML.replace(/<\/?a(|\s+[^>]+)>/g, '');
				
		var d = new Date();
		var curr_date = d.getDate();
		var curr_month = d.getMonth() + 1; //Months are zero based
		var curr_year = d.getFullYear();
		var tanggal = curr_date + "-" + curr_month + "-" + curr_year;
		
		var ctx = {worksheet: tanggal || 'Worksheet', table: table_html}


		if(browserTester('chrome')) {
		
			a.href = uri + base64(format(template, ctx));
			//setting the file name
			a.download = 'data'+tanggal+'.xls';
			//triggering the function
			a.click();
			//just in case, prevent default behaviour	
		} else if(browserTester('mozilla')) {
			window.location.href = uri + base64(format(template, ctx))
		}

        e.preventDefault();

    });
</script>